package com.example.mvvmtemplate.page.main;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mvvmtemplate.R;
import com.example.mvvmtemplate.adapter.MainViewPagerAdapter;
import com.example.mvvmtemplate.base.viewmodel.BaseMVVMActivity;
import com.example.mvvmtemplate.model.MainViewModel;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseMVVMActivity<MainViewModel> {

    @Override
    public int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public Class<MainViewModel> getViewModelClass() {
        return MainViewModel.class;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        ViewPager2 viewPager = findViewById(R.id.viewPager);

        //禁用预加载
        viewPager.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(HomeFragment.getInstance());
        fragments.add(StockFragment.getInstance());
        fragments.add(DataFragment.getInstance());
        fragments.add(MineFragment.getInstance());
        MainViewPagerAdapter viewPagerAdapter = new MainViewPagerAdapter(this, fragments);
        viewPager.setAdapter(viewPagerAdapter);

        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setCustomView(getView("首页", R.drawable.home_selector));
                    break;
                case 1:
                    tab.setCustomView(getView("库存", R.drawable.stock_selector));
                    break;
                case 2:
                    tab.setCustomView(getView("统计", R.drawable.data_selector));
                    break;
                case 3:
                    tab.setCustomView(getView("我的", R.drawable.mine_selector));
                    break;
            }
        }).attach();
    }

    private View getView(String text, @DrawableRes int resId) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.item_view, null);
        ImageView iv_view = view.findViewById(R.id.iv_view);
        TextView tv_view = view.findViewById(R.id.tv_view);
        tv_view.setText(text);
        iv_view.setImageResource(resId);
        return view;
    }
}